<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>svg</title>
  <style>
    body {
      text-align: center;
    }

    svg {
      background-color: #dddddd;
    }
  </style>
</head>

<body>
  <h3>svg 图形</h3>
  <svg width="500" height="400" id="svg">
    <circle cx="250" cy="200" r="50" fill="#00f" fill-opacity="0.2" stroke="#f00" stroke-opacity="0.8"></circle>
  </svg>


  <br>
  <hr>
  <h3>练习</h3>
  <svg width="500" height="400" id="svg2">

  </svg>

  <script>
    var svg = document.getElementById("svg");
    var cricle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    cricle.setAttribute("cx", "100");
    cricle.setAttribute("cy", "200");
    cricle.setAttribute("r", "50");
    cricle.setAttribute("fill", "#fc0");
    svg.appendChild(cricle);

    // 点击放大
    cricle.onclick = function () {
      var r = this.getAttribute("r");
      // r是字符串 
      cricle.setAttribute("r", r * 1.1);
    }




    // 练习
    var svg2 = document.getElementById("svg2");
    for (let i = 0; i < 30; i++) {
      var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
      var x = Math.random() * 500;
      var y = Math.random() * 400;
      var r = 3 + Math.random() * 50;
      var o = Math.random();
      circle.setAttribute("cx", x);
      circle.setAttribute("cy", y);
      circle.setAttribute("r", r);
      circle.setAttribute("fill", cr());
      circle.setAttribute("fill-opacity", o);
      svg2.appendChild(circle);

      circle.addEventListener("click", function () {
        this.onclick = null; 
        var time = setInterval(() => {
          var r = this.getAttribute("r");
          this.setAttribute("r", r*1.05);

          // var opacity = parseFloat(this.getAttribute("fill-opacity"));
          var opacity = this.getAttribute("fill-opacity");
          this.setAttribute("fill-opacity", opacity*0.9);
          if(opacity < 0.1){
            clearInterval(time);
            svg2.removeChild(this);
          }

        }, 200);

      });
    }

    function cr() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return `rgb(${r},${g},${b})`;
    }
  </script>
</body>

</html>